package org.jl.spring.aop.annotation;

import com.alibaba.fastjson2.JSON;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.concurrent.ConcurrentHashMap;

@Aspect
@Component
@Slf4j
public class SysCacheAspect {

    private final ConcurrentHashMap<String, CacheData> cachePool = new ConcurrentHashMap<>();

    /**
     * 将数据放入缓存中
     *
     * @param key         缓存键
     * @param value       缓存值
     * @param expiredTime 缓存过期时间，单位为秒
     */
    public void put(String key, Object value, long expiredTime) {
        long endTime = System.currentTimeMillis() + expiredTime * 1000;
        CacheData cacheData = new CacheData(value, endTime);
        cachePool.put(key, cacheData);
    }

    /**
     * 获取缓存数据
     *
     * @param key 缓存键
     * @return 缓存值，如果缓存过期或者不存在，则返回null
     */
    public Object get(String key) {
        CacheData cacheData = cachePool.get(key);
        if (cacheData != null && !cacheData.isExpired()) {
            return cacheData.value();
        } else {
            cachePool.remove(key);
            return null;
        }
    }

    @Pointcut("@annotation(SysCache)")
    public void cache() {
    }

    @Around(value = "cache()")
    public Object cacheAround(ProceedingJoinPoint joinPoint) throws Throwable {
        String className = joinPoint.getTarget().getClass().getName();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        SysCache sysCache = method.getAnnotation(SysCache.class);
        long expireTime = 30;
        if (sysCache.expireTime() > 0) {
            expireTime = sysCache.expireTime();
        }
        String key = className + "." + method.getName();
        Object proceed = joinPoint.proceed();
        Object value = get(key);
        if (value == null) {
            put(key, proceed, expireTime);
            log.info("Returns ===》 " + JSON.toJSONString(proceed) + " 方法返回值");
            return proceed;
        } else {
            log.info("Returns ===》 " + JSON.toJSONString(proceed) + " 使用缓存值");
            return value;
        }
    }

    private record CacheData(@Getter Object value, long endTime) {

        /**
         * 判断缓存是否过期
         *
         * @return true表示过期，false表示未过期
         */
        public boolean isExpired() {
            return System.currentTimeMillis() > endTime;
        }
    }
}
